package org.davidtrevien.com.imput.omi.panels.center.planning.datenavigation;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import org.davidtrevien.com.imput.omi.panels.center.planning.DateEditionEvent;
import org.davidtrevien.com.imput.omi.panels.center.planning.DateEditionListener;
import org.davidtrevien.utils.controler.Controller;

public class DateNavigationCtrl
	extends Controller<DateNavigationView> {

	protected int year;
	protected int month;
	
	protected List<DateEditionListener> dateEditionListeners = new ArrayList<DateEditionListener>();
	
	public DateNavigationCtrl() {
		initValuesForToday();
		initComponent();
		initListener();
	}

	protected void initValuesForToday() {
		Calendar calendar = Calendar.getInstance(Locale.FRENCH);
		this.year = calendar.get(Calendar.YEAR);
		this.month = 0;//calendar.get(Calendar.MONTH)+1;
	}
	
	private void initComponent() {
		this.view = new DateNavigationView();
		
		this.view.year.setText(this.year+"");
		this.view.month.setMonth(this.month);
	}
	
	private void initListener() {
		this.view.nextYear.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				DateNavigationCtrl.this.year++;
				DateNavigationCtrl.this.view.year.setText(DateNavigationCtrl.this.year+"");
				notifyDateChanged();
			}
		});

		this.view.prevYear.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				DateNavigationCtrl.this.year--;
				DateNavigationCtrl.this.view.year.setText(DateNavigationCtrl.this.year+"");
				notifyDateChanged();
			}
		});
		
		this.view.nextMonth.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				DateNavigationCtrl.this.month++;
				DateNavigationCtrl.this.view.month.setMonth(DateNavigationCtrl.this.month);
				notifyDateChanged();
			}
		});

		this.view.prevMonth.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				DateNavigationCtrl.this.month--;
				DateNavigationCtrl.this.view.month.setMonth(DateNavigationCtrl.this.month);
				notifyDateChanged();
			}
		});

		this.view.today.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				initValuesForToday();
				DateNavigationCtrl.this.view.year.setText(DateNavigationCtrl.this.year+"");
				DateNavigationCtrl.this.view.month.setMonth(DateNavigationCtrl.this.month);
				notifyDateChanged();
			}
		});
	}

	public boolean add(DateEditionListener e) {
		return this.dateEditionListeners.add(e);
	}
	
	protected void notifyDateChanged() {
		DateEditionEvent e = new DateEditionEvent();
		e.setMonth(this.month);
		e.setYear(this.year);
		for (DateEditionListener l : this.dateEditionListeners) {
			l.dateChanged(e);
		}
	}
	
}
